﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Threading;

namespace PSE.AuditLogging.StorageService.Configuration
{
    public class ConfigurationReader
    {
        static string _configFile;
        static object _syncRoot = new object();
        static LogServiceConfigurationSection _logServiceConfiguration;

        public static LogServiceConfigurationSection LogServiceConfiguration
        {
            get
            {
                lock (_syncRoot)
                {
                    if (string.IsNullOrEmpty(_configFile))
                        _configFile = Path.Combine(Path.GetDirectoryName(System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath), "PSE.AuditLogging.StorageService.exe");


                    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(_configFile);

                    if (config == null)
                        throw new ConfigurationErrorsException(string.Format("Configuration file '{0}' not found.", _configFile));

                    if (_logServiceConfiguration == null)
                        _logServiceConfiguration = config.GetSection(Constants.LOGSERVICE_SECTION_NAME) as LogServiceConfigurationSection;

                    if (_logServiceConfiguration == null)
                        throw new ConfigurationErrorsException(string.Format("Configuration section '{0}' not found in config file.", Constants.LOGSERVICE_SECTION_NAME));

                    return _logServiceConfiguration;
                }
            }
        }
    }
}
